// Package meth meth/mac.go
package meth

import (
	"fmt"
	"os/exec"
	"regexp"
	"strings"
)

type ARPEntry struct {
	IP  string
	MAC string
}

// GetARPTable MAC
func GetARPTable() (s string) {
	cmd := exec.Command("arp", "-a")
	output, err := cmd.CombinedOutput()
	if err != nil {
		return ""
	}
	return string(output)
}

// ParseARP 解析ARP命令输出
func ParseARP(arpTable string) ([]ARPEntry, error) {
	pattern := `(?:$)?(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})(?:$)?\s+(?:at\s+)?((?:[0-9A-Fa-f]{2}[-:]){5}[0-9A-Fa-f]{2})`
	re := regexp.MustCompile(pattern)
	var entries []ARPEntry
	lines := strings.Split(arpTable, "\n")

	for _, line := range lines {
		matches := re.FindStringSubmatch(line)
		if len(matches) >= 3 {
			ip := matches[1]
			rawMac := matches[2]
			mac := formatMAC(rawMac)
			entries = append(entries, ARPEntry{IP: ip, MAC: mac})
		}
	}

	if len(entries) == 0 {
		return nil, fmt.Errorf("no valid ARP entries found")
	}
	return entries, nil
}

// 统一MAC地址格式
func formatMAC(raw string) string {
	// 移除所有非十六进制字符（保留分隔符）
	clean := strings.ReplaceAll(raw, "-", ":")
	// 转换为大写
	return strings.ToUpper(clean)
}
